<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="ZooKeeper突击，看这篇就够了, Gtwff">
    <meta name="description" content="">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="referrer" content="no-referrer-when-downgrade">
    <!-- Global site tag (gtag.js) - Google Analytics -->

<script async src="https://www.googletagmanager.com/gtag/js?id="></script>
<script>
    window.dataLayer = window.dataLayer || [];
    function gtag() {
        dataLayer.push(arguments);
    }

    gtag('js', new Date());
    gtag('config', '');
</script>


    <title>ZooKeeper突击，看这篇就够了 | Gtwff</title>
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>

<meta name="generator" content="Hexo 5.4.0"></head>



   <style>
    body{
       background-image: url(https://cdn.jsdelivr.net/gh/Tokisaki-Galaxy/res/site/medias/background.jpg);
       background-repeat:no-repeat;
       background-size:cover;
       background-attachment:fixed;
    }
</style>



<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">Gtwff</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友情链接</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">Gtwff</div>
        <div class="logo-desc">
            
            Never really desperate, only the lost of the soul.
            
        </div>
    </div>

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友情链接
		</a>
          
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://gitee.com/kuangty/kuangty" class="waves-effect waves-light" target="_blank">
                <i class="fab fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>


        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://gitee.com/kuangty/kuangty" class="github-corner tooltipped hide-on-med-and-down" target="_blank"
   data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewBox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
              fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
              fill="currentColor" class="octo-body"></path>
    </svg>
</a>
        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/featureimages/3.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">ZooKeeper突击，看这篇就够了</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        padding: 35px 0 15px 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        padding-bottom: 30px;
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/Zookeeper-%E7%AA%81%E5%87%BB/">
                                <span class="chip bg-color">Zookeeper 突击</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/ZooKeeper/" class="post-category">
                                ZooKeeper
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2021-11-10
                </div>
                

                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-check fa-fw"></i>更新日期:&nbsp;&nbsp;
                    2022-03-27
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    8.4k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>阅读时长:&nbsp;&nbsp;
                    34 分
                </div>
                

                
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="far fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
        </div>
        <hr class="clearfix">

        
        <!-- 是否加载使用自带的 prismjs. -->
        <link rel="stylesheet" href="/libs/prism/prism.css">
        

        
        <!-- 代码块折行 -->
        <style type="text/css">
            code[class*="language-"], pre[class*="language-"] { white-space: pre-wrap !important; }
        </style>
        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <h2 id="1、Zookeeper快速入门"><a href="#1、Zookeeper快速入门" class="headerlink" title="1、Zookeeper快速入门"></a>1、Zookeeper快速入门</h2><h3 id="1-1、Zookeeper-概述"><a href="#1-1、Zookeeper-概述" class="headerlink" title="1.1、Zookeeper 概述"></a>1.1、Zookeeper 概述</h3><p>Zookeeper 是一个基于观察者模式设计的分布式服务管理框架，负责存储和管理数据，接受观察者的注册，一旦这些数据的状态发生变化，Zookeeper 就将负责通知已经在Zookeeper上注册的那些观察者做出相应的反应。</p>
<p><img src="https://cdn.jsdelivr.net/gh/kuangtianyu/img/img/zookeeper1.jpg" alt="img"></p>
<h3 id="1-2、Zookeeper-的特点"><a href="#1-2、Zookeeper-的特点" class="headerlink" title="1.2、Zookeeper 的特点"></a>1.2、Zookeeper 的特点</h3><img src="https://gitee.com/kuangtf/blogImage/raw/master/img/Zookeeper2.jpg" style="zoom:80%;" />

<p>1）：Zookeeper ：一个领导者 （Leader），多个跟随者 （Follower）组成的集群。</p>
<p>2）：集群中只要有半数以上节点存活，Zookeeper 集群就能正常服务，所以Zookeeper 适合安装奇数台服务器。</p>
<p>3）：全局数据一致：每个Server保存一份相同的数据副本，Client无论连接到哪个Server，数据都是一致的。</p>
<p>4）：更新请求顺序执行，来自同一个Client的更新请求按其发送顺序依次执行。</p>
<p>5）：数据更新原子性，一次数据更新要么成功，要么失败。</p>
<p>6）：实时性，在一定时间范围内，Client能读到最新数据。</p>
<h3 id="1-3、数据结构"><a href="#1-3、数据结构" class="headerlink" title="1.3、数据结构"></a>1.3、数据结构</h3><p>Zookeeper 数据模型的结构与Unix 文件系统很类似，像一个分布式的小文件存储系统，整体上可以看作是一棵树，每个节点称做一个 ZNode。每一个 ZNode 默认能够存储 1MB 的数据，每个 ZNode 都可以通过其路径唯一标识。  </p>
<img src="https://gitee.com/kuangtf/blogImage/raw/master/img/Zookeeper3.jpg" style="zoom:80%;" />

<h3 id="1-4、应用场景"><a href="#1-4、应用场景" class="headerlink" title="1.4、应用场景"></a>1.4、应用场景</h3><ul>
<li><p>提供的服务包括：统一命名服务、统一配置管理、统一集群管理、服务器节点动态上下线、软负载均衡等 。</p>
</li>
<li><p>同一服务命名：在分布式环境下，经常需要对应用/服务进行统一命名，便于识别。例如：IP不容易记住，而域名容易记住。</p>
</li>
</ul>
<img src="https://gitee.com/kuangtf/blogImage/raw/master/img/zookeeper4.jpg" style="zoom:80%;" />

<ul>
<li>统一配置管理<ul>
<li>分布式环境下，配置文件同步非常常见：1、一般要求一个集群中，所有节点的配置信息是一致的，比如Kafka集群。2、对配置文件修改之后，希望能够快速同步到各个节点上。</li>
<li>配置管理可交由Zookeeper实现：1、可将配置信息写入Zookeeper上的一个Znode。2、各个客户端服务器监听这个Znode。3、一旦Znode中的数据被修改，Zookeeper将通知各个客户端服务器。</li>
</ul>
</li>
</ul>
<img src="https://gitee.com/kuangtf/blogImage/raw/master/img/zookeeper5.jpg" style="zoom:80%;" />

<ul>
<li>同一集群管理<ul>
<li>分布式环境中，实时掌握每个节点的状态是必要的：可根据节点实时状态做出一些调整。</li>
<li>Zookeeper可以实现实时监控节点状态变化：1、可将节点信息写入Zookeeper上的一个Znode。2、监听这个Znode可获取它的实时状态变化。</li>
</ul>
</li>
</ul>
<img src="https://gitee.com/kuangtf/blogImage/raw/master/img/zookeeper6.jpg" style="zoom: 80%;" />

<ul>
<li>服务器动态上下线</li>
</ul>
<img src="https://gitee.com/kuangtf/blogImage/raw/master/img/zookeeper7.jpg" style="zoom: 80%;" />

<ul>
<li>负载均衡：在Zookeeper中记录每台服务器的访问数，让访问数最少的服务器去处理最新的客户daunt请求。</li>
</ul>
<img src="https://gitee.com/kuangtf/blogImage/raw/master/img/zookeeper8.jpg" style="zoom: 80%;" />

<h2 id="2、Zookeeper操作"><a href="#2、Zookeeper操作" class="headerlink" title="2、Zookeeper操作"></a>2、Zookeeper操作</h2><h3 id="2-1、简单操作："><a href="#2-1、简单操作：" class="headerlink" title="2.1、简单操作："></a>2.1、简单操作：</h3><p>1、启动Zookeeper：</p>
<pre class="line-numbers language-none"><code class="language-none">[root@192 zookeeper-3.5.7]# bin&#x2F;zkServer.sh start<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>2、查看进程是否启动</p>
<pre class="line-numbers language-none"><code class="language-none">[root@192 zookeeper-3.5.7]# jps
102109 Jps
20286 QuorumPeerMain<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<p>3、查看状态</p>
<pre class="line-numbers language-none"><code class="language-none">[root@192 zookeeper-3.5.7]# bin&#x2F;zkServer.sh status
ZooKeeper JMX enabled by default
Using config: &#x2F;opt&#x2F;module&#x2F;zookeeper-3.5.7&#x2F;bin&#x2F;..&#x2F;conf&#x2F;zoo.cfg
Client port found: 2181. Client address: localhost.
Mode: standalone<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>4、启动客户端</p>
<pre class="line-numbers language-none"><code class="language-none">[root@192 zookeeper-3.5.7]# bin&#x2F;zkCli.sh<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>5、退出客户端</p>
<pre class="line-numbers language-none"><code class="language-none">[zk: localhost:2181(CONNECTED) 0] quit<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>6、停止Zookeeper</p>
<pre class="line-numbers language-none"><code class="language-none">[root@192 zookeeper-3.5.7]# bin&#x2F;zkServer.sh stop<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<h3 id="2-2、配置参数解读"><a href="#2-2、配置参数解读" class="headerlink" title="2.2、配置参数解读"></a>2.2、配置参数解读</h3><p>Zookeeper中的配置文件zoo.cfg中参数含义解读如下  ：</p>
<ul>
<li>tickTime = 2000： 通信心跳时间， Zookeeper服务器与客户端心跳时间，单位毫秒  </li>
<li>initLimit = 10： LF初始通信时限  ：Leader和Follower初始连接时能容忍的最多心跳数（tickTime的数量）  </li>
<li>syncLimit = 5： LF同步通信时限  ：Leader和Follower之间通信时间如果超过syncLimit * tickTime， Leader认为Follwer死<br>  掉，从服务器列表中删除Follwer  </li>
<li>dataDir： 保存Zookeeper中的数据  。注意： 默认的tmp目录，容易被Linux系统定期删除，所以一般不用默认的tmp目录。  </li>
<li>clientPort = 2181：客户端连接端口，通常不做修改。  </li>
</ul>
<h2 id="3、Zookeeper-集群操作"><a href="#3、Zookeeper-集群操作" class="headerlink" title="3、Zookeeper 集群操作"></a>3、Zookeeper 集群操作</h2><h3 id="3-1、集群操作"><a href="#3-1、集群操作" class="headerlink" title="3.1、集群操作"></a>3.1、集群操作</h3><h4 id="3-1-1、集群安装"><a href="#3-1-1、集群安装" class="headerlink" title="3.1.1、集群安装"></a>3.1.1、集群安装</h4><p>集群规划：在 hadoop102、 hadoop103 和 hadoop104 三个节点上都部署 Zookeeper。  </p>
<ul>
<li>思考：如果是 10 台服务器，需要部署多少台 Zookeeper？  </li>
</ul>
<p><strong>解压安装</strong>  </p>
<p>1、在 hadoop102 解压 Zookeeper 安装包到/opt/module/目录下  ：</p>
<pre class="line-numbers language-none"><code class="language-none">[192@hadoop102 software]$ tar -zxvf apache-zookeeper-3.5.7-bin.tar.gz -C &#x2F;opt&#x2F;module&#x2F;<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>2、修改 apache-zookeeper-3.5.7-bin 名称为 zookeeper-3.5.7  ：</p>
<pre class="line-numbers language-none"><code class="language-none">[192@hadoop102 module]$ mv apache-zookeeper-3.5.7-bin&#x2F;zookeeper-3.5.7<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p><strong>配置服务器编号</strong>  </p>
<p>1、在/opt/module/zookeeper-3.5.7/这个目录下创建 zkData  </p>
<pre class="line-numbers language-none"><code class="language-none">[192@hadoop102 zookeeper-3.5.7]$ mkdir zkData<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>2、在/opt/module/zookeeper-3.5.7/zkData 目录下创建一个 myid 的文件  </p>
<pre class="line-numbers language-none"><code class="language-none">[192@hadoop102 zkData]$ vi myid<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>在文件中添加与 server 对应的编号（注意：上下不要有空行，左右不要有空格） </p>
<blockquote>
<p>注意： 添加 myid 文件，一定要在 Linux 里面创建，在 notepad++里面很可能乱码      </p>
</blockquote>
<p>3、拷贝配置好的 zookeeper 到其他机器上，并分别在 hadoop103、 hadoop104 上修改 myid 文件中内容为 3、 4 。</p>
<pre class="line-numbers language-none"><code class="language-none">[192@hadoop102 module ]$ xsync zookeeper-3.5.7<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p><strong>配置zoo.cfg文件</strong>  </p>
<p>1、重命名/opt/module/zookeeper-3.5.7/conf 这个目录下的 zoo_sample.cfg 为 zoo.cfg  </p>
<pre class="line-numbers language-none"><code class="language-none">[192@hadoop102 conf]$ mv zoo_sample.cfg zoo.cfg<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>2、打开 zoo.cfg 文件  </p>
<pre class="line-numbers language-none"><code class="language-none">[192@hadoop102 conf]$ vim zoo.cfg<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>修改数据存储路径配置：</p>
<pre class="line-numbers language-none"><code class="language-none">dataDir&#x3D;&#x2F;opt&#x2F;module&#x2F;zookeeper-3.5.7&#x2F;zkData<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>增加如下配置  </p>
<pre class="line-numbers language-none"><code class="language-none">#######################cluster##########################
server.2&#x3D;hadoop102:2888:3888
server.3&#x3D;hadoop103:2888:3888
server.4&#x3D;hadoop104:2888:3888<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<p>3、配置参数解读  </p>
<pre class="line-numbers language-none"><code class="language-none">server.A&#x3D;B:C:D。<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>A 是一个数字，表示这个是第几号服务器：集群模式下配置一个文件 myid， 这个文件在 dataDir 目录下，这个文件里面有一个数据就是 A 的值， Zookeeper 启动时读取此文件，拿到里面的数据与 zoo.cfg 里面的配置信息比较从而判断到底是哪个 server。<br>B 是这个服务器的地址；<br>C 是这个服务器 Follower 与集群中的 Leader 服务器交换信息的端口；<br>D 是万一集群中的 Leader 服务器挂了，需要一个端口来重新进行选举，选出一个新的 Leader，而这个端口就是用来执行选举时服务器相互通信的端口。  </p>
<p>4、同步 zoo.cfg 配置文件  </p>
<pre class="line-numbers language-shell" data-language="shell"><code class="language-shell"><span class="token punctuation">[</span><span class="token number">192</span>@hadoop102 conf<span class="token punctuation">]</span>$ xsync zoo.cfg<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p><strong>集群操作</strong>  </p>
<p>1、分别启动 Zookeeper  </p>
<pre class="line-numbers language-none"><code class="language-none">[192@hadoop102 zookeeper-3.5.7]$ bin&#x2F;zkServer.sh start
[192@hadoop103 zookeeper-3.5.7]$ bin&#x2F;zkServer.sh start
[192@hadoop104 zookeeper-3.5.7]$ bin&#x2F;zkServer.sh start<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<p>2、查看状态</p>
<pre class="line-numbers language-none"><code class="language-none">[192@hadoop102 zookeeper-3.5.7]# bin&#x2F;zkServer.sh status
JMX enabled by defaultUsing config: &#x2F;opt&#x2F;module&#x2F;zookeeper-3.5.7&#x2F;bin&#x2F;..&#x2F;conf&#x2F;zoo.cfgMode: follower
[192@hadoop103 zookeeper-3.5.7]# bin&#x2F;zkServer.sh status
JMX enabled by defaultUsing config: &#x2F;opt&#x2F;module&#x2F;zookeeper-3.5.7&#x2F;bin&#x2F;..&#x2F;conf&#x2F;zoo.cfgMode: leader
[192@hadoop104 zookeeper-3.4.5]# bin&#x2F;zkServer.sh status
JMX enabled by defaultUsing config: &#x2F;opt&#x2F;module&#x2F;zookeeper-3.5.7&#x2F;bin&#x2F;..&#x2F;conf&#x2F;zoo.cfgMode: follower<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h4 id="3-1-2-选举机制"><a href="#3-1-2-选举机制" class="headerlink" title="3.1.2 选举机制"></a>3.1.2 选举机制</h4><img src="https://gitee.com/kuangtf/blogImage/raw/master/img/zookeeper9.jpg" style="zoom: 80%;" />

<p>第一次启动</p>
<ul>
<li>服务器1启动，发起一次选举。服务器1投自己一票。此时服务器1票数一票，不够半数以上（3票），选举无法完成，服务器1状态保持为 LOOKING；</li>
<li>服务器2启动，在发起一次选举。服务器1和2分别投自己一票并交换选票信息：此时服务器1发现服务器2的myid比自己目前投票推举的（服务器1）大，更改选票为推举服务器2。此时服务器1票数0票，服务器2票数2票，没有半数以上结果，选举无法完成，服务器1和2保持状态LOOKING。</li>
<li>服务器3启动，发起一次选举。此时服务器1和2都会更改选票为服务器3.此次投票结果：服务器1为0票，服务器2为0票，服务器3为3票，此时服务器3的票数已经超过半数，服务器3当选Leader。服务器1，2更改状态为FOLLOWING，服务器3更改状态为LEADING。</li>
<li>服务器4启动，发起一次选举。此时服务器1,2,3已经不是LOOKING状态，不会更改选票信息。交换选票结果：服务器3位3票，服务器4为1票。此时服务器4服从多数，更改选票信息为服务器3，并更改状态为FOLLOING。</li>
<li>服务器5启动，同4一样当小弟。</li>
</ul>
<blockquote>
<p>SID：服务器ID。用来唯一标识一台Zookeeper集群中的机器，每台机器不能重复，和myid一致。</p>
<p>ZXID：事务ID。ZXID是一个事务ID，用来表示一次服务器状态的变更。在某一时刻，集群中的每台机器的ZXID值不一定完全一致，这和Zookeeper服务器对于客户端“更新请求”的处理逻辑有关。</p>
<p>Epoch：每个Leader任期的代号。没有Leader时同一轮投票过程中的逻辑时钟值是相同的。每投完一次票这个数据就会增加。</p>
</blockquote>
<img src="https://gitee.com/kuangtf/blogImage/raw/master/img/zookeeper10.jpg" style="zoom: 80%;" />

<p>非第一次启动</p>
<ul>
<li>当Zookeeper集群中的一台服务器出现以下两种情况之一时，就会开始进入Leader选举：<ul>
<li>服务器初始化启动</li>
<li>服务器运行期间无法和Leader保持连接</li>
</ul>
</li>
<li>而当一台机器进入Leader选举流程时，当前集群也可能会处于以下两种状态：<ul>
<li>集群中本来就已经存在一个Leader：机器试图去选举Leader时，会被告知当前服务器的Leader信息，对于该机器来说， 仅仅需要和Leader机器建立连接，并进行状态同步即可。</li>
<li>集群中确实不存在Leader：假设Zookeeper由5台服务器组成，SID分别为1、2、3、4、5，ZXID分别为8、8、8、7、7，并且此时SID为3的服务器是Leader。某一时刻3和5服务器出现故障，因此开始进行Leader选举。选举规则：1、EPOCH大的直接胜出，2、EPOCH相同，事务id大的胜出，3、事务id相同，服务器id大的胜出。</li>
</ul>
</li>
</ul>
<h4 id="3-1-3-ZK-集群启动停止脚本"><a href="#3-1-3-ZK-集群启动停止脚本" class="headerlink" title="3.1.3 ZK 集群启动停止脚本"></a>3.1.3 ZK 集群启动停止脚本</h4><ul>
<li>在 hadoop102 的/home/ktf/bin 目录下创建脚本  </li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">[192@hadoop102 bin]$ vim zk.sh<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>在脚本中编写如下内容  </p>
<pre class="line-numbers language-shell" data-language="shell"><code class="language-shell"><span class="token shebang important">#!/bin/bashcase $1 in"start")&#123;	</span>
<span class="token keyword">for</span> <span class="token for-or-select variable">i</span> <span class="token keyword">in</span> hadoop102 hadoop103 hadoop104	<span class="token keyword">do</span>	
	<span class="token builtin class-name">echo</span> ---------- zookeeper <span class="token variable">$i</span> 启动 ------------	
	<span class="token function">ssh</span> <span class="token variable">$i</span> <span class="token string">"/opt/module/zookeeper-3.5.7/bin/zkServer.shstart"</span>	<span class="token keyword">done</span>
<span class="token punctuation">&#125;</span><span class="token punctuation">;</span><span class="token punctuation">;</span><span class="token string">"stop"</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>	
<span class="token keyword">for</span> <span class="token for-or-select variable">i</span> <span class="token keyword">in</span> hadoop102 hadoop103 hadoop104	<span class="token keyword">do</span>	
	<span class="token builtin class-name">echo</span> ---------- zookeeper <span class="token variable">$i</span> 停止 ------------
	<span class="token function">ssh</span> <span class="token variable">$i</span> <span class="token string">"/opt/module/zookeeper-3.5.7/bin/zkServer.shstop"</span>	<span class="token keyword">done</span>
<span class="token punctuation">&#125;</span><span class="token punctuation">;</span><span class="token punctuation">;</span><span class="token string">"status"</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>	
<span class="token keyword">for</span> <span class="token for-or-select variable">i</span> <span class="token keyword">in</span> hadoop102 hadoop103 hadoop104	<span class="token keyword">do</span>	
	<span class="token builtin class-name">echo</span> ---------- zookeeper <span class="token variable">$i</span> 状态 ------------	
	<span class="token function">ssh</span> <span class="token variable">$i</span> <span class="token string">"/opt/module/zookeeper-3.5.7/bin/zkServer.shstatus"</span>	<span class="token keyword">done</span>
<span class="token punctuation">&#125;</span><span class="token punctuation">;</span><span class="token punctuation">;</span>
<span class="token keyword">esac</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<ul>
<li>增加脚本执行权限  </li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">[192@hadoop102 bin]$ chmod u+x zk.sh<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<ul>
<li>Zookeeper 集群启动脚本  </li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">[192@hadoop102 module]$ zk.sh start<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<ul>
<li>Zookeeper 集群停止脚本  </li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">[192@hadoop102 module]$ zk.sh stop<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<h3 id="3-2、客户端命令行操作"><a href="#3-2、客户端命令行操作" class="headerlink" title="3.2、客户端命令行操作"></a>3.2、客户端命令行操作</h3><h4 id="3-2-1、命令行基本语法"><a href="#3-2-1、命令行基本语法" class="headerlink" title="3.2.1、命令行基本语法"></a>3.2.1、命令行基本语法</h4><table>
<thead>
<tr>
<th>命令基本语法</th>
<th>功能描述</th>
</tr>
</thead>
<tbody><tr>
<td>help</td>
<td>显示所有操作命令</td>
</tr>
<tr>
<td>ls path</td>
<td>使用 ls 命令来查看当前 znode 的子节点 [可监听]</td>
</tr>
<tr>
<td></td>
<td>-w 监听子节点变化</td>
</tr>
<tr>
<td></td>
<td>-s 附加次级信息</td>
</tr>
<tr>
<td>create</td>
<td>普通创建</td>
</tr>
<tr>
<td></td>
<td>-s 含有序列</td>
</tr>
<tr>
<td></td>
<td>-e 临时（重启或者超时消失）</td>
</tr>
<tr>
<td>get path</td>
<td>获得节点的值 [可监听]</td>
</tr>
<tr>
<td></td>
<td>-w 监听节点内容变化</td>
</tr>
<tr>
<td></td>
<td>-s 附加次级信息</td>
</tr>
<tr>
<td>set</td>
<td>设置节点的具体值</td>
</tr>
<tr>
<td>stat</td>
<td>查看节点状态</td>
</tr>
<tr>
<td>delete</td>
<td>删除节点</td>
</tr>
<tr>
<td>deleteall</td>
<td>递归删除节点</td>
</tr>
</tbody></table>
<ul>
<li>启动客户端</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">[192@hadoop102 zookeeper-3.5.7]$ bin&#x2F;zkCli.sh -server hadoop102:2181<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<ul>
<li>显示所有操作命令</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">[zk: hadoop102:2181(CONNECTED) 1] help<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<h4 id="3-2-2-znode-节点数据信息"><a href="#3-2-2-znode-节点数据信息" class="headerlink" title="3.2.2 znode 节点数据信息"></a>3.2.2 znode 节点数据信息</h4><ul>
<li>查看当前znode中所包含的内容  </li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">[zk: hadoop102:2181(CONNECTED) 0] ls &#x2F;[zookeeper]<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<ul>
<li>查看当前节点详细数据  </li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">[zk: hadoop102:2181(CONNECTED) 5] ls -s &#x2F;[zookeeper]cZxid &#x3D; 0x0    
&#x2F;&#x2F; 创建节点的事务 zxidctime &#x3D; Thu Jan 01 08:00:00 CST 1970   
&#x2F;&#x2F; znode 被创建的毫秒数（从 1970 年开始）mZxid &#x3D; 0x0 
&#x2F;&#x2F; znode 最后更新的事务 zxidmtime &#x3D; Thu Jan 01 08:00:00 CST 1970 
&#x2F;&#x2F; znode 最后修改的毫秒数（从 1970 年开始）pZxid &#x3D; 0x0  
&#x2F;&#x2F; znode 最后更新的子节点 zxidcversion &#x3D; -1   
&#x2F;&#x2F; znode 子节点变化号， znode 子节点修改次数dataVersion &#x3D; 0 
&#x2F;&#x2F; znode 数据变化号aclVersion &#x3D; 0   
&#x2F;&#x2F; znode 访问控制列表的变化号ephemeralOwner &#x3D; 0x0 
&#x2F;&#x2F; 如果是临时节点，这个是 znode 拥有者的 session id。如果不是临时节点则是 0。dataLength &#x3D; 0 
&#x2F;&#x2F; znode 的数据长度numChildren &#x3D; 1    &#x2F;&#x2F;  znode 子节点数量<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h4 id="3-2-3-节点类型（持久-短暂-有序号-无序号）"><a href="#3-2-3-节点类型（持久-短暂-有序号-无序号）" class="headerlink" title="3.2.3 节点类型（持久/短暂/有序号/无序号）"></a>3.2.3 节点类型（持久/短暂/有序号/无序号）</h4><ul>
<li>持久（Persistent）：客户端和服务器断开连接后，创建的节点不删除</li>
<li>短暂（Ephemeral）：客户端和服务器断开连接后，创建的节点自己删除</li>
</ul>
<img src="https://gitee.com/kuangtf/blogImage/raw/master/img/zookeeper11.jpg" style="zoom:80%;" />

<ul>
<li>持久化目录节点：客户端与Zookeeper断开连接后，该节点依旧存在</li>
<li>持久化顺序编号目录节点：客户端与Zookeeper断开连接后，该节点依旧存在，只是Zookeeper给 该节点名称进行顺序编号</li>
<li>临时目录节点：客户端与Zookeeper断开连接后，该节点被删除</li>
<li>临时顺序编号目录节点：客户端与Zookeeper断开连接后，该节点被删除，只是Zookeeper给该节点名称进行顺序编号。</li>
</ul>
<blockquote>
<p>说明：创建Znode时设置顺序表示，Znode名称后会附加一个值，顺序号是一个单调递增的计数器，由父节点维护。</p>
<p>注意：在分布式系统中，顺序号可以被用于为所有的事件进行全局排序，这样客户端可以通过顺序号推断事件的顺序。</p>
</blockquote>
<p>1、分别创建2个普通节点（永久节点 + 不带序号）  </p>
<pre class="line-numbers language-none"><code class="language-none">[zk: localhost:2181(CONNECTED) 3] create &#x2F;sanguo &quot;diaochan&quot;Created &#x2F;sanguo
[zk: localhost:2181(CONNECTED) 4] create &#x2F;sanguo&#x2F;shuguo &quot;liubei&quot;Created &#x2F;sanguo&#x2F;shuguo<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<blockquote>
<p>注意：创建节点时， 要赋值  </p>
</blockquote>
<p>2、获得节点的值</p>
<pre class="line-numbers language-none"><code class="language-none">[zk: localhost:2181(CONNECTED) 5] get -s &#x2F;sanguodiaochan
cZxid &#x3D; 0x100000003
ctime &#x3D; Wed Aug 29 00:03:23 CST 2018m
Zxid &#x3D; 0x100000003
mtime &#x3D; Wed Aug 29 00:03:23 CST 2018
pZxid &#x3D; 0x100000004
cversion &#x3D; 1data
Version &#x3D; 0acl
Version &#x3D; 0ephemeral
Owner &#x3D; 0x0
dataLength &#x3D; 7numChildren &#x3D; 1
[zk: localhost:2181(CONNECTED) 6] get -s &#x2F;sanguo&#x2F;shuguoliubei
cZxid &#x3D; 0x100000004
ctime &#x3D; Wed Aug 29 00:04:35 CST 2018
mZxid &#x3D; 0x100000004
mtime &#x3D; Wed Aug 29 00:04:35 CST 2018
pZxid &#x3D; 0x100000004
cversion &#x3D; 0
dataVersion &#x3D; 0aclVersion &#x3D; 0ephemeralOwner &#x3D; 0x0dataLength &#x3D; 6numChildren &#x3D; 0<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>3、创建带序号的节点（永久节点 + 带序号）  </p>
<ul>
<li>先创建一个普通的根节点/sanguo/weiguo  </li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">[zk: localhost:2181(CONNECTED) 1] create &#x2F;sanguo&#x2F;weiguo &quot;caocao&quot;Created &#x2F;sanguo&#x2F;weiguo<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<ul>
<li>创建带序号的节点</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">[zk: localhost:2181(CONNECTED) 2] create -s &#x2F;sanguo&#x2F;weiguo&#x2F;zhangliao 
&quot;zhangliao&quot;Created &#x2F;sanguo&#x2F;weiguo&#x2F;zhangliao0000000000
[zk: localhost:2181(CONNECTED) 3] create -s &#x2F;sanguo&#x2F;weiguo&#x2F;zhangliao 
&quot;zhangliao&quot;Created &#x2F;sanguo&#x2F;weiguo&#x2F;zhangliao0000000001
[zk: localhost:2181(CONNECTED) 4] create -s &#x2F;sanguo&#x2F;weiguo&#x2F;xuchu 
&quot;xuchu&quot;Created &#x2F;sanguo&#x2F;weiguo&#x2F;xuchu0000000002<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<blockquote>
<p>如果原来没有序号节点，序号从 0 开始依次递增。 如果原节点下已有 2 个节点，则再排序时从 2 开始，以此类推。  </p>
</blockquote>
<p>4、创建短暂节点（短暂节点 + 不带序号 or 带序号）  </p>
<ul>
<li>创建短暂的不带序号的节点  </li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">[zk: localhost:2181(CONNECTED) 7] create -e &#x2F;sanguo&#x2F;wuguo &quot;zhouyu&quot;Created &#x2F;sanguo&#x2F;wuguo<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<ul>
<li>创建短暂的带序号的节点  </li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">[zk: localhost:2181(CONNECTED) 2] create -e -s &#x2F;sanguo&#x2F;wuguo 
&quot;zhouyu&quot;Created &#x2F;sanguo&#x2F;wuguo0000000001<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<ul>
<li>在当前客户端是能查看到的  </li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">[zk: localhost:2181(CONNECTED) 3] ls &#x2F;sanguo[wuguo, wuguo0000000001, shuguo]<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<ul>
<li>退出当前客户端然后再重启客户端  </li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">[zk: localhost:2181(CONNECTED) 12] quit[atguigu@hadoop104 zookeeper-3.5.7]$ bin&#x2F;zkCli.sh<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<ul>
<li>再次查看根目录下短暂节点已经删除  </li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">[zk: localhost:2181(CONNECTED) 0] ls &#x2F;sanguo[shuguo]<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<ul>
<li>修改节点数据值  </li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">[zk: localhost:2181(CONNECTED) 6] set &#x2F;sanguo&#x2F;weiguo &quot;simayi&quot;<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<h4 id="3-2-4-监听器原理"><a href="#3-2-4-监听器原理" class="headerlink" title="3.2.4 监听器原理"></a>3.2.4 监听器原理</h4><ul>
<li><p>客户端注册监听它关心的目录节点，当目录节点发生变化（数据改变、节点删除、子目录节点增加删除）时， ZooKeeper 会通知客户端。监听机制保证 ZooKeeper 保存的任何的数据的任何改变都能快速的响应到监听了该节点的应用程序  </p>
</li>
<li><p>监听器详解：</p>
<ul>
<li>首先要有一个main（）线程</li>
<li>在main线程中创建Zookeeper客户端，这时就会创建两个线程，一个负责网络连接通信（connet），一个负责监听（listener）。</li>
<li>通过connect线程将注册的监听事件发送给Zookeeper。</li>
<li>在Zookeeper的注册监听列表中将注册监听事件添加到列表中。</li>
<li>Zookeeper监听到有数据或路径变化，就会将这个消息发送给listener线程。</li>
<li>listener线程内部调用了process（）方法。</li>
</ul>
</li>
<li><p>常见的监听</p>
<ul>
<li>监听节点数据的变化：get path [watch]</li>
<li>监听子节点增减的变化：ls path [watch]</li>
</ul>
</li>
</ul>
<img src="https://gitee.com/kuangtf/blogImage/raw/master/img/zookeeper12.jpg" style="zoom:80%;" />

<p>1、节点的值变化监听</p>
<ul>
<li>在hadoop104 主机上注册监听/sanguo 节点数据变化  </li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">[zk: localhost:2181(CONNECTED) 26] get -w &#x2F;sanguo<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<ul>
<li>在 hadoop103 主机上修改/sanguo 节点的数据  </li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">[zk: localhost:2181(CONNECTED) 1] set &#x2F;sanguo &quot;xisi<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<ul>
<li>观察 hadoop104 主机收到数据变化的监听  </li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">WATCHER::WatchedEvent state:SyncConnected type:NodeDataChangedpath:&#x2F;sanguo<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<blockquote>
<p>注意：在hadoop103再多次修改/sanguo的值， hadoop104上不会再收到监听。因为注册一次，只能监听一次。想再次监听，需要再次注册  </p>
</blockquote>
<p>2、节点的子节点变化监听（路径变化）  </p>
<ul>
<li>在 hadoop104 主机上注册监听/sanguo 节点的子节点变化  </li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">[zk: localhost:2181(CONNECTED) 1] ls -w &#x2F;sanguo[shuguo, weiguo]<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<ul>
<li>在 hadoop103 主机/sanguo 节点上创建子节点  </li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">[zk: localhost:2181(CONNECTED) 2] create &#x2F;sanguo&#x2F;jin &quot;simayi&quot;Created &#x2F;sanguo&#x2F;jin<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<ul>
<li>观察 hadoop104 主机收到子节点变化的监听  </li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">WATCHER::WatchedEvent state:SyncConnected type:NodeChildrenChangedpath:&#x2F;sanguo<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<blockquote>
<p>注意： 节点的路径变化，也是注册一次，生效一次。想多次生效，就需要多次注册。  </p>
</blockquote>
<h4 id="3-2-5-节点删除与查看"><a href="#3-2-5-节点删除与查看" class="headerlink" title="3.2.5 节点删除与查看"></a>3.2.5 节点删除与查看</h4><ul>
<li>删除节点  </li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">[zk: localhost:2181(CONNECTED) 4] delete &#x2F;sanguo&#x2F;jin<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<ul>
<li>递归删除节点  </li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">[zk: localhost:2181(CONNECTED) 15] deleteall &#x2F;sanguo&#x2F;shuguo<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<ul>
<li>查看节点状态  </li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">[zk: localhost:2181(CONNECTED) 17] stat &#x2F;sanguoc
Zxid &#x3D; 0x100000003
ctime &#x3D; Wed Aug 29 00:03:23 CST 2018
mZxid &#x3D; 0x100000011
mtime &#x3D; Wed Aug 29 00:21:23 CST 2018
pZxid &#x3D; 0x100000014
cversion &#x3D; 9dataVersion &#x3D; 1aclVersion &#x3D; 0ephemeralOwner &#x3D; 0x0dataLength &#x3D; 4numChildren &#x3D; 1<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h3 id="3-3-客户端向服务端写数据流程"><a href="#3-3-客户端向服务端写数据流程" class="headerlink" title="3.3 客户端向服务端写数据流程"></a>3.3 客户端向服务端写数据流程</h3><ul>
<li>写流程之写入请求直接发送给Leader节点</li>
</ul>
<img src="https://gitee.com/kuangtf/blogImage/raw/master/img/zookeeper13.jpg" style="zoom:80%;" />

<ul>
<li>写流程之写入请求发送给follower节点</li>
</ul>
<img src="https://gitee.com/kuangtf/blogImage/raw/master/img/zookeeper14.jpg" style="zoom:80%;" />



<h2 id="4、ZooKeeper-分布式锁"><a href="#4、ZooKeeper-分布式锁" class="headerlink" title="4、ZooKeeper 分布式锁"></a>4、ZooKeeper 分布式锁</h2><h3 id="1、概述"><a href="#1、概述" class="headerlink" title="1、概述"></a>1、概述</h3><p>什么叫做分布式锁呢？</p>
<ul>
<li>比如说”进程 1”在使用该资源的时候，会先去获得锁， “进程 1”获得锁以后会对该资源 保持独占，这样其他进程就无法访问该资源， “进程 1”用完该资源以后就将锁释放掉，让其他进程来获得锁，那么通过这个锁机制，我们就能保证了分布式系统中多个进程能够有序的访问该临界资源。那么我们把这个分布式环境下的这个锁叫作分布式锁。  </li>
</ul>
<img src="https://gitee.com/kuangtf/blogImage/raw/master/img/zookeeper15.jpg" style="zoom: 80%;" />

<h3 id="2、原生-Zookeeper-实现分布式锁案例"><a href="#2、原生-Zookeeper-实现分布式锁案例" class="headerlink" title="2、原生 Zookeeper 实现分布式锁案例"></a>2、原生 Zookeeper 实现分布式锁案例</h3><p>原生 Zookeeper 实现分布式锁案例  </p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">import</span> <span class="token namespace">org<span class="token punctuation">.</span>apache<span class="token punctuation">.</span>zookeeper<span class="token punctuation">.</span></span><span class="token operator">*</span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token namespace">org<span class="token punctuation">.</span>apache<span class="token punctuation">.</span>zookeeper<span class="token punctuation">.</span>data<span class="token punctuation">.</span></span><span class="token class-name">Stat</span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token namespace">java<span class="token punctuation">.</span>io<span class="token punctuation">.</span></span><span class="token class-name">IOException</span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span></span><span class="token class-name">Collections</span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span></span><span class="token class-name">List</span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span><span class="token class-name">CountDownLatch</span><span class="token punctuation">;</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">DistributedLock</span> <span class="token punctuation">&#123;</span>   
    <span class="token comment">// zookeeper server 列表    </span>
    <span class="token keyword">private</span> <span class="token class-name">String</span> connectString <span class="token operator">=</span><span class="token string">"hadoop102:2181,hadoop103:2181,hadoop104:2181"</span><span class="token punctuation">;</span>   
    <span class="token comment">// 超时时间  </span>
    <span class="token keyword">private</span> <span class="token keyword">int</span> sessionTimeout <span class="token operator">=</span> <span class="token number">2000</span><span class="token punctuation">;</span>   
    <span class="token keyword">private</span> <span class="token class-name">ZooKeeper</span> zk<span class="token punctuation">;</span>  
    <span class="token keyword">private</span> <span class="token class-name">String</span> rootNode <span class="token operator">=</span> <span class="token string">"locks"</span><span class="token punctuation">;</span>
    <span class="token keyword">private</span> <span class="token class-name">String</span> subNode <span class="token operator">=</span> <span class="token string">"seq-"</span><span class="token punctuation">;</span>  
    <span class="token comment">// 当前 client 等待的子节点    </span>
    <span class="token keyword">private</span> <span class="token class-name">String</span> waitPath<span class="token punctuation">;</span>  
    <span class="token comment">//ZooKeeper 连接  </span>
    <span class="token keyword">private</span> <span class="token class-name">CountDownLatch</span> connectLatch <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">CountDownLatch</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>  
    <span class="token comment">//ZooKeeper 节点等待    </span>
    <span class="token keyword">private</span> <span class="token class-name">CountDownLatch</span> waitLatch <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">CountDownLatch</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>   
    <span class="token comment">// 当前 client 创建的子节点  </span>
    <span class="token keyword">private</span> <span class="token class-name">String</span> currentNode<span class="token punctuation">;</span>  
    <span class="token comment">// 和 zk 服务建立连接，并创建根节点 </span>
    <span class="token keyword">public</span> <span class="token class-name">DistributedLock</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">IOException</span><span class="token punctuation">,</span> <span class="token class-name">InterruptedException</span><span class="token punctuation">,</span> <span class="token class-name">KeeperException</span> <span class="token punctuation">&#123;</span>  
        zk <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ZooKeeper</span><span class="token punctuation">(</span>connectString<span class="token punctuation">,</span> sessionTimeout<span class="token punctuation">,</span> <span class="token keyword">new</span> <span class="token class-name">Watcher</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>   
            <span class="token annotation punctuation">@Override</span>                   
            <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">process</span><span class="token punctuation">(</span><span class="token class-name">WatchedEvent</span> event<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>     
                <span class="token comment">// 连接建立时, 打开 latch, 唤醒 wait 在该 latch 上的线程   </span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span>event<span class="token punctuation">.</span><span class="token function">getState</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">==</span> <span class="token class-name">Event<span class="token punctuation">.</span>KeeperState<span class="token punctuation">.</span>SyncConnected</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>        
                    connectLatch<span class="token punctuation">.</span><span class="token function">countDown</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>         
                <span class="token punctuation">&#125;</span>                          
                <span class="token comment">// 发生了 waitPath 的删除事件   </span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span>event<span class="token punctuation">.</span><span class="token function">getType</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">==</span> <span class="token class-name">Event<span class="token punctuation">.</span>EventType<span class="token punctuation">.</span>NodeDeleted</span> <span class="token operator">&amp;&amp;</span> event<span class="token punctuation">.</span><span class="token function">getPath</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span>waitPath<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>                             
                    waitLatch<span class="token punctuation">.</span><span class="token function">countDown</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>                    
                <span class="token punctuation">&#125;</span>                        
            <span class="token punctuation">&#125;</span>             
        <span class="token punctuation">&#125;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>      
        <span class="token comment">// 等待连接建立    </span>
        connectLatch<span class="token punctuation">.</span><span class="token function">await</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>      
        <span class="token comment">//获取根节点状态      </span>
        <span class="token class-name">Stat</span> stat <span class="token operator">=</span> zk<span class="token punctuation">.</span><span class="token function">exists</span><span class="token punctuation">(</span><span class="token string">"/"</span> <span class="token operator">+</span> rootNode<span class="token punctuation">,</span> <span class="token boolean">false</span><span class="token punctuation">)</span><span class="token punctuation">;</span>     
        <span class="token comment">//如果根节点不存在，则创建根节点，根节点类型为永久节点  </span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>stat <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>          
            <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"根节点不存在"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>    
            zk<span class="token punctuation">.</span><span class="token function">create</span><span class="token punctuation">(</span><span class="token string">"/"</span> <span class="token operator">+</span> rootNode<span class="token punctuation">,</span> <span class="token keyword">new</span> <span class="token keyword">byte</span><span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span><span class="token punctuation">,</span>   
                      <span class="token class-name">ZooDefs<span class="token punctuation">.</span>Ids</span><span class="token punctuation">.</span>OPEN_ACL_UNSAFE<span class="token punctuation">,</span> <span class="token class-name">CreateMode</span><span class="token punctuation">.</span>PERSISTENT<span class="token punctuation">)</span><span class="token punctuation">;</span>   
        <span class="token punctuation">&#125;</span>   
    <span class="token punctuation">&#125;</span>    
    <span class="token comment">// 加锁方法  </span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">zkLock</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>   
        <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>         
            <span class="token comment">//在根节点下创建临时顺序节点，返回值为创建的节点路径     </span>
            currentNode <span class="token operator">=</span> zk<span class="token punctuation">.</span><span class="token function">create</span><span class="token punctuation">(</span><span class="token string">"/"</span> <span class="token operator">+</span> rootNode <span class="token operator">+</span> <span class="token string">"/"</span> <span class="token operator">+</span> subNode<span class="token punctuation">,</span>  
                                    <span class="token keyword">null</span><span class="token punctuation">,</span> <span class="token class-name">ZooDefs<span class="token punctuation">.</span>Ids</span><span class="token punctuation">.</span>OPEN_ACL_UNSAFE<span class="token punctuation">,</span> 
                                    <span class="token class-name">CreateMode</span><span class="token punctuation">.</span>EPHEMERAL_SEQUENTIAL<span class="token punctuation">)</span><span class="token punctuation">;</span>   
            <span class="token comment">// wait 一小会, 让结果更清晰一些       </span>
            <span class="token class-name">Thread</span><span class="token punctuation">.</span><span class="token function">sleep</span><span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">)</span><span class="token punctuation">;</span>       
            <span class="token comment">// 注意, 没有必要监听"/locks"的子节点的变化情况  </span>
            <span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">></span></span> childrenNodes <span class="token operator">=</span> zk<span class="token punctuation">.</span><span class="token function">getChildren</span><span class="token punctuation">(</span><span class="token string">"/"</span> <span class="token operator">+</span> rootNode<span class="token punctuation">,</span> <span class="token boolean">false</span><span class="token punctuation">)</span><span class="token punctuation">;</span>    
            <span class="token comment">// 列表中只有一个子节点, 那肯定就是 currentNode , 说明 client 获得锁  </span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>childrenNodes<span class="token punctuation">.</span><span class="token function">size</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">==</span> <span class="token number">1</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>    
                <span class="token keyword">return</span><span class="token punctuation">;</span>         
            <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>      
                <span class="token comment">//对根节点下的所有临时顺序节点进行从小到大排序         </span>
                <span class="token class-name">Collections</span><span class="token punctuation">.</span><span class="token function">sort</span><span class="token punctuation">(</span>childrenNodes<span class="token punctuation">)</span><span class="token punctuation">;</span>       
                <span class="token comment">//当前节点名称         </span>
                <span class="token class-name">String</span> thisNode <span class="token operator">=</span> currentNode<span class="token punctuation">.</span><span class="token function">substring</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token string">"/"</span> <span class="token operator">+</span>  rootNode <span class="token operator">+</span> <span class="token string">"/"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">length</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>   
                <span class="token comment">//获取当前节点的位置              </span>
                <span class="token keyword">int</span> index <span class="token operator">=</span> childrenNodes<span class="token punctuation">.</span><span class="token function">indexOf</span><span class="token punctuation">(</span>thisNode<span class="token punctuation">)</span><span class="token punctuation">;</span>    
                <span class="token keyword">if</span> <span class="token punctuation">(</span>index <span class="token operator">==</span> <span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>            
                    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"数据异常"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>   
                <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token keyword">if</span> <span class="token punctuation">(</span>index <span class="token operator">==</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>                
                    <span class="token comment">// index == 0, 说明 thisNode 在列表中最小, 当前 client 获得锁      </span>
                    <span class="token keyword">return</span><span class="token punctuation">;</span>                  
                <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>        
                    <span class="token comment">// 获得排名比 currentNode 前 1 位的节点   </span>
                    <span class="token keyword">this</span><span class="token punctuation">.</span>waitPath <span class="token operator">=</span> <span class="token string">"/"</span> <span class="token operator">+</span> rootNode <span class="token operator">+</span> <span class="token string">"/"</span> <span class="token operator">+</span> childrenNodes<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span>index <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>      
                    <span class="token comment">// 在 waitPath 上注册监听器, 当 waitPath 被删除时, zookeeper 会回调监听器的 process 方法            </span>
                    zk<span class="token punctuation">.</span><span class="token function">getData</span><span class="token punctuation">(</span>waitPath<span class="token punctuation">,</span> <span class="token boolean">true</span><span class="token punctuation">,</span> <span class="token keyword">new</span> <span class="token class-name">Stat</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>       
                    <span class="token comment">//进入等待锁状态                    </span>
                    waitLatch<span class="token punctuation">.</span><span class="token function">await</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>               
                    <span class="token keyword">return</span><span class="token punctuation">;</span>               
                <span class="token punctuation">&#125;</span>            
            <span class="token punctuation">&#125;</span>      
        <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">KeeperException</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>    
            e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>   
        <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">InterruptedException</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>  
            e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>      
        <span class="token punctuation">&#125;</span>
    <span class="token punctuation">&#125;</span>   
    <span class="token comment">// 解锁方法   </span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">zkUnlock</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>     
        <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>      
            zk<span class="token punctuation">.</span><span class="token function">delete</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>currentNode<span class="token punctuation">,</span> <span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>      
        <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">InterruptedException</span> <span class="token operator">|</span> <span class="token class-name">KeeperException</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span> 
            e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>    
        <span class="token punctuation">&#125;</span> 
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>分布式锁测试  </p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">import</span> <span class="token namespace">org<span class="token punctuation">.</span>apache<span class="token punctuation">.</span>zookeeper<span class="token punctuation">.</span></span><span class="token class-name">KeeperException</span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token namespace">java<span class="token punctuation">.</span>io<span class="token punctuation">.</span></span><span class="token class-name">IOException</span><span class="token punctuation">;</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">DistributedLockTest</span> <span class="token punctuation">&#123;</span>   
    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">InterruptedException</span><span class="token punctuation">,</span> <span class="token class-name">IOException</span><span class="token punctuation">,</span> <span class="token class-name">KeeperException</span> <span class="token punctuation">&#123;</span>   
        <span class="token comment">// 创建分布式锁 1      </span>
        <span class="token keyword">final</span> <span class="token class-name">DistributedLock</span> lock1 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">DistributedLock</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>  
        <span class="token comment">// 创建分布式锁 2      </span>
        <span class="token keyword">final</span> <span class="token class-name">DistributedLock</span> lock2 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">DistributedLock</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>  
        <span class="token keyword">new</span> <span class="token class-name">Thread</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Runnable</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>      
            <span class="token annotation punctuation">@Override</span>         
            <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>  
                <span class="token comment">// 获取锁对象     </span>
                <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>           
                    lock1<span class="token punctuation">.</span><span class="token function">zkLock</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>      
                    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"线程 1 获取锁"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>                 
                    <span class="token class-name">Thread</span><span class="token punctuation">.</span><span class="token function">sleep</span><span class="token punctuation">(</span><span class="token number">5</span> <span class="token operator">*</span> <span class="token number">1000</span><span class="token punctuation">)</span><span class="token punctuation">;</span>          
                    lock1<span class="token punctuation">.</span><span class="token function">zkUnlock</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>  
                    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"线程 1 释放锁"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>   
                <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">Exception</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>   
                    e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>       
                <span class="token punctuation">&#125;</span>         
            <span class="token punctuation">&#125;</span>  
        <span class="token punctuation">&#125;</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>      
        <span class="token keyword">new</span> <span class="token class-name">Thread</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Runnable</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>     
            <span class="token annotation punctuation">@Override</span>          
            <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>   
                <span class="token comment">// 获取锁对象      </span>
                <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>                
                    lock2<span class="token punctuation">.</span><span class="token function">zkLock</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>    
                    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"线程 2 获取锁"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>           
                    <span class="token class-name">Thread</span><span class="token punctuation">.</span><span class="token function">sleep</span><span class="token punctuation">(</span><span class="token number">5</span> <span class="token operator">*</span> <span class="token number">1000</span><span class="token punctuation">)</span><span class="token punctuation">;</span>         
                    lock2<span class="token punctuation">.</span><span class="token function">zkUnlock</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>       
                    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"线程 2 释放锁"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>  
                <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">Exception</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>         
                    e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>         
                <span class="token punctuation">&#125;</span>        
            <span class="token punctuation">&#125;</span>       
        <span class="token punctuation">&#125;</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> 
    <span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>输出：</p>
<pre class="line-numbers language-none"><code class="language-none">线程 1 获取锁线程 1 释放锁线程 2 获取锁线程 2 释放锁<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<h3 id="3、Curator-框架实现分布式锁"><a href="#3、Curator-框架实现分布式锁" class="headerlink" title="3、Curator 框架实现分布式锁"></a>3、Curator 框架实现分布式锁</h3><p>原生的 Java API 开发存在的问题 ：</p>
<ul>
<li>会话连接是异步的，需要自己去处理。比如使用 CountDownLatch  </li>
<li>Watch 需要重复注册，不然就不能生效  </li>
<li>开发的复杂性还是比较高的  </li>
<li>不支持多节点删除和创建。需要自己去递归  </li>
</ul>
<p>Curator 是一个专门解决分布式锁的框架，解决了原生 Java API 开发分布式遇到的问题  </p>
<p>Curator 案例实操  ：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">import</span> <span class="token namespace">org<span class="token punctuation">.</span>apache<span class="token punctuation">.</span>curator<span class="token punctuation">.</span></span><span class="token class-name">RetryPolicy</span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token namespace">org<span class="token punctuation">.</span>apache<span class="token punctuation">.</span>curator<span class="token punctuation">.</span>framework<span class="token punctuation">.</span></span><span class="token class-name">CuratorFramework</span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token namespace">org<span class="token punctuation">.</span>apache<span class="token punctuation">.</span>curator<span class="token punctuation">.</span>framework<span class="token punctuation">.</span></span><span class="token class-name">CuratorFrameworkFactory</span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token namespace">org<span class="token punctuation">.</span>apache<span class="token punctuation">.</span>curator<span class="token punctuation">.</span>framework<span class="token punctuation">.</span>recipes<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span><span class="token class-name">InterProcessLock</span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token namespace">org<span class="token punctuation">.</span>apache<span class="token punctuation">.</span>curator<span class="token punctuation">.</span>framework<span class="token punctuation">.</span>recipes<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span><span class="token class-name">InterProcessMutex</span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token namespace">org<span class="token punctuation">.</span>apache<span class="token punctuation">.</span>curator<span class="token punctuation">.</span>retry<span class="token punctuation">.</span></span><span class="token class-name">ExponentialBackoffRetry</span><span class="token punctuation">;</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">CuratorLockTest</span> <span class="token punctuation">&#123;</span>    
    <span class="token keyword">private</span> <span class="token class-name">String</span> rootNode <span class="token operator">=</span> <span class="token string">"/locks"</span><span class="token punctuation">;</span>
    <span class="token comment">// zookeeper server 列表   </span>
    <span class="token keyword">private</span> <span class="token class-name">String</span> connectString <span class="token operator">=</span> <span class="token string">"hadoop102:2181,hadoop103:2181,hadoop104:2181"</span><span class="token punctuation">;</span> 
    <span class="token comment">// connection 超时时间</span>
    <span class="token keyword">private</span> <span class="token keyword">int</span> connectionTimeout <span class="token operator">=</span> <span class="token number">2000</span><span class="token punctuation">;</span>   
    <span class="token comment">// session 超时时间   </span>
    <span class="token keyword">private</span> <span class="token keyword">int</span> sessionTimeout <span class="token operator">=</span> <span class="token number">2000</span><span class="token punctuation">;</span>
    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>     
        <span class="token keyword">new</span> <span class="token class-name">CuratorLockTest</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">test</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>   
    <span class="token punctuation">&#125;</span>   
    <span class="token comment">// 测试 </span>
    <span class="token keyword">private</span> <span class="token keyword">void</span> <span class="token function">test</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>     
        <span class="token comment">// 创建分布式锁 1   </span>
        <span class="token keyword">final</span> <span class="token class-name">InterProcessLock</span> lock1 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">InterProcessMutex</span><span class="token punctuation">(</span><span class="token function">getCuratorFramework</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> rootNode<span class="token punctuation">)</span><span class="token punctuation">;</span>  
        <span class="token comment">// 创建分布式锁 2       </span>
        <span class="token keyword">final</span> <span class="token class-name">InterProcessLock</span> lock2 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">InterProcessMutex</span><span class="token punctuation">(</span><span class="token function">getCuratorFramework</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> rootNode<span class="token punctuation">)</span><span class="token punctuation">;</span>  
        <span class="token keyword">new</span> <span class="token class-name">Thread</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Runnable</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>      
            <span class="token annotation punctuation">@Override</span>           
            <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>    
                <span class="token comment">// 获取锁对象       </span>
                <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>              
                    lock1<span class="token punctuation">.</span><span class="token function">acquire</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>     
                    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"线程 1 获取锁"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>      
                    <span class="token comment">// 测试锁重入             </span>
                    lock1<span class="token punctuation">.</span><span class="token function">acquire</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>     
                    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"线程 1 再次获取锁"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>   
                    <span class="token class-name">Thread</span><span class="token punctuation">.</span><span class="token function">sleep</span><span class="token punctuation">(</span><span class="token number">5</span> <span class="token operator">*</span> <span class="token number">1000</span><span class="token punctuation">)</span><span class="token punctuation">;</span>           
                    lock1<span class="token punctuation">.</span><span class="token function">release</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>          
                    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"线程 1 释放锁"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>         
                    lock1<span class="token punctuation">.</span><span class="token function">release</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>            
                    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"线程 1 再次释放锁"</span><span class="token punctuation">)</span><span class="token punctuation">;</span> 
                <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">Exception</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>       
                    e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>     
                <span class="token punctuation">&#125;</span>          
            <span class="token punctuation">&#125;</span>  
        <span class="token punctuation">&#125;</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>   
        <span class="token keyword">new</span> <span class="token class-name">Thread</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Runnable</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>  
            <span class="token annotation punctuation">@Override</span>         
            <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>           
                <span class="token comment">// 获取锁对象            </span>
                <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>                 
                    lock2<span class="token punctuation">.</span><span class="token function">acquire</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>     
                    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"线程 2 获取锁"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>         
                    <span class="token comment">// 测试锁重入              </span>
                    lock2<span class="token punctuation">.</span><span class="token function">acquire</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>         
                    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"线程 2 再次获取锁"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>   
                    <span class="token class-name">Thread</span><span class="token punctuation">.</span><span class="token function">sleep</span><span class="token punctuation">(</span><span class="token number">5</span> <span class="token operator">*</span> <span class="token number">1000</span><span class="token punctuation">)</span><span class="token punctuation">;</span>       
                    lock2<span class="token punctuation">.</span><span class="token function">release</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>       
                    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"线程 2 释放锁"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>     
                    lock2<span class="token punctuation">.</span><span class="token function">release</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>             
                    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"线程 2 再次释放锁"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>   
                <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">Exception</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>  
                    e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>  
                <span class="token punctuation">&#125;</span>           
            <span class="token punctuation">&#125;</span>   
        <span class="token punctuation">&#125;</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>   
    <span class="token punctuation">&#125;</span>    
    <span class="token comment">// 分布式锁初始化    </span>
    <span class="token keyword">public</span> <span class="token class-name">CuratorFramework</span> getCuratorFramework <span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>      
        <span class="token comment">//重试策略，初试时间 3 秒，重试 3 次  </span>
        <span class="token class-name">RetryPolicy</span> policy <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ExponentialBackoffRetry</span><span class="token punctuation">(</span><span class="token number">3000</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment">//通过工厂创建 Curator </span>
        <span class="token class-name">CuratorFramework</span> client <span class="token operator">=</span> <span class="token class-name">CuratorFrameworkFactory</span><span class="token punctuation">.</span><span class="token function">builder</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">connectString</span><span class="token punctuation">(</span>connectString<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">connectionTimeoutMs</span><span class="token punctuation">(</span>connectionTimeout<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">sessionTimeoutMs</span><span class="token punctuation">(</span>sessionTimeout<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">retryPolicy</span><span class="token punctuation">(</span>policy<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">build</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>   
        <span class="token comment">//开启连接     </span>
        client<span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> 
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"zookeeper 初始化完成..."</span><span class="token punctuation">)</span><span class="token punctuation">;</span>  
        <span class="token keyword">return</span> client<span class="token punctuation">;</span>   
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<ul>
<li>观察控制台变化：  </li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">线程 1 获取锁线程 1 再次获取锁线程 1 释放锁线程 1 再次释放锁线程 2 获取锁线程 2 再次获取锁线程 2 释放锁线程 2 再次释放锁<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<h2 id="5、Zookeeper源码分析"><a href="#5、Zookeeper源码分析" class="headerlink" title="5、Zookeeper源码分析"></a>5、Zookeeper源码分析</h2><h3 id="1、Paxos算法"><a href="#1、Paxos算法" class="headerlink" title="1、Paxos算法"></a>1、Paxos算法</h3><ul>
<li>Paxos算法：一种基于消息传递且具备高度容错特性的一致性算法。</li>
<li>Paxos算法解决的问题：就是如何快速正确的在一个分布式系统中对某个数据值达成一致，并且保证无论发生任何异常都不会破坏整个系统的一致性。</li>
</ul>
<img src="https://gitee.com/kuangtf/blogImage/raw/master/img/zookeeper16.jpg" style="zoom:67%;" />

<ul>
<li>在一个Paxos系统中，首先将所有节点划分为Proposer（提议者），Acceptor（接收者），和Learner（学习者）。（注意：每个节点都可以身兼数职）</li>
</ul>
<img src="https://gitee.com/kuangtf/blogImage/raw/master/img/zookeeper17.jpg" style="zoom:67%;" />

<ul>
<li>一个完整的Paxos算法流程分为三个阶段：<ul>
<li>Prepare准备阶段：Proposer向多个Acceptor发出Propose请求Promise（承诺），Acceptor针对收到的Propose请求进行Promise（承诺）</li>
<li>Accept接受阶段：Proposer收到多数Acceptor承诺的Promise后，向Acceptor发出Propose请求，Acceptor针对收到的Propose请求进行Accept处理</li>
<li>Learn学习阶段：Propose将形成的决议发送给所有Learners</li>
</ul>
</li>
</ul>
<img src="https://gitee.com/kuangtf/blogImage/raw/master/img/zookeeper18.jpg" style="zoom:67%;" />

<ul>
<li>算法流程<ul>
<li>Prepare: Proposer生成全局唯一且递增的Proposal ID,向所有Acceptor发送Propose请求，这里无需携带提案内容，只携带Proposal ID即可。</li>
<li>Promise:Acceptor收到Propose请求后，做出“两个承诺，一个应答”。<ul>
<li>不再接受Proposal ID小于等于(注意：这里是&lt;=)当前请求的Propose请求。</li>
<li>不再接受Proposal ID小于(注意：这里是&lt; )当前请求的Accept请求。</li>
<li>不违背以前做出的承诺下，回复已经Accept过的提案中Proposal ID最大的那个提案的Value和Proposal ID,没有则返回空值。</li>
</ul>
</li>
<li>Propose: Proposer收到多数Acceptor的Promise应答后，从应答中选择Proposal ID最大的提案的Value,作为本次要发起的提案。如果所有应答的提案Value均为空值，则可以自己随意决定提案Value。然后携带当前Proposal ID,向所有Acceptor发送     Propose请求。</li>
<li>Accept: Acceptor收到Propose请求后，在不违背自己之前做出的承诺下，接受并持久化当前Proposal ID和提案Value。</li>
<li>Learn: Proposer收到多数Acceptor的Accept后，决议形成，将形成的决议发送给所有Learner。</li>
</ul>
</li>
<li>下面我们针对上述描述做三种情况的推演举例：为了简化流程，我们这里不设置 Learner。  </li>
</ul>
<img src="https://gitee.com/kuangtf/blogImage/raw/master/img/zookeeper19.jpg" style="zoom:80%;" />

<ul>
<li>情况1：有A1、A2、A3、A4、A5  5位议员，就税率问题进行决议。<ul>
<li>A1发起1号Proposal的Propose，等待Promise承诺；  </li>
<li>A2-A5回应Promise</li>
<li>A1在收到两份回复时就会发起税率10%的Proposal；</li>
<li>A2-A5回应Accept</li>
<li>通过Proposal，税率10%。</li>
</ul>
</li>
</ul>
<img src="https://gitee.com/kuangtf/blogImage/raw/master/img/zookeeper20.jpg" style="zoom:80%;" />

<ul>
<li>情况2：现在我们假设在A1提出提案的同时，A5决定将税率定为20%<ul>
<li>A1， A5同时发起Propose（序号分别为1， 2）</li>
<li>A2承诺A1， A4承诺A5， A3行为成为关键</li>
<li>情况1： A3先收到A1消息，承诺A1。</li>
<li>A1发起Proposal（1， 10%）， A2， A3接受。</li>
<li>之后A3又收到A5消息， 回复A1： （1， 10%），并承诺A5。</li>
<li>A5发起Proposal（2， 20%）， A3， A4接受。之后A1， A5同时广播决议。</li>
</ul>
</li>
</ul>
<img src="https://gitee.com/kuangtf/blogImage/raw/master/img/zookeeper21.jpg" style="zoom:80%;" />

<ul>
<li><p>现在我们假设在A1提出提案的同时, A5决定将税率定为20%</p>
<ul>
<li>A1， A5同时发起Propose（序号分别为1， 2）</li>
<li>A2承诺A1， A4承诺A5， A3行为成为关键</li>
<li>情况2： A3先收到A1消息，承诺A1。之后立刻收到A5消息，承诺A5。</li>
<li>A1发起Proposal（1， 10%），无足够响应， A1重新Propose （序号3）， A3再次承诺A1。</li>
<li>A5发起Proposal（2， 20%），无足够相应。 A5重新Propose （序号4）， A3再次承诺A5。</li>
<li>……</li>
</ul>
</li>
<li><p>造成这种情况的原因是系统中有一个以上的 Proposer，多个 Proposers 相互争夺 Acceptor，造成迟迟无法达成一致的情况。 针对这种情况，一种改进的 Paxos 算法被提出：从系统中选出一个节点作为 Leader，只有 Leader 能够发起提案。 这样，一次 Paxos 流程中只有一个Proposer，不会出现活锁的情况，此时只会出现例子中第一种情况。  </p>
</li>
<li><p>Paxos 算法缺陷：在网络复杂的情况下，一个应用 Paxos 算法的分布式系统，可能很久无法收敛，甚至陷入活锁的情况。  </p>
</li>
</ul>
<h3 id="2、ZAB-协议"><a href="#2、ZAB-协议" class="headerlink" title="2、ZAB 协议"></a>2、ZAB 协议</h3><p>什么是 ZAB 算法 ：Zab 借鉴了 Paxos 算法，是特别为 Zookeeper 设计的支持崩溃恢复的原子广播协议。基于该协议， Zookeeper 设计为只有一台客户端（Leader）负责处理外部的写事务请求，然后Leader 客户端将数据同步到其他 Follower 节点。 即 Zookeeper 只有一个 Leader 可以发起提案 。</p>
<p>Zab 协议包括两种基本的模式： 消息广播、 崩溃恢复 。</p>
<img src="https://gitee.com/kuangtf/blogImage/raw/master/img/zookeeper22.jpg" style="zoom:67%;" />

<h4 id="2-1、消息广播"><a href="#2-1、消息广播" class="headerlink" title="2.1、消息广播"></a>2.1、消息广播</h4><ul>
<li><p>客户端发起一个写操作请求。</p>
</li>
<li><p>Leader服务器将客户端的请求转化为事务Proposal 提案， 同时为每个Proposal 分配一个全局的ID， 即zxid。</p>
</li>
<li><p>Leader服务器为每个Follower服务器分配一个单独的队列， 然后将需要广播的 Proposal依次放到队列中去， 并且根据FIFO策略进行消息发送。</p>
</li>
<li><p>Follower接收到Proposal后， 会首先将其以事务日志的方式写入本地磁盘中， 写入成功后向Leader反馈一个Ack响应消息。</p>
</li>
<li><p>Leader接收到超过半数以上Follower的Ack响应消息后， 即认为消息发送成功， 可以发送commit消息。</p>
</li>
<li><p>Leader向所有Follower广播commit消息， 同时自身也会完成事务提交。 Follower 接收到commit消息后， 会将上一条事务提交。</p>
</li>
<li><p>Zookeeper采用Zab协议的核心， 就是只要有一台服务器提交了Proposal， 就要确保所有的服务器最终都能正确提交Proposal。</p>
</li>
<li><p>ZAB协议针对事务请求的处理过程类似于一个两阶段提交过程</p>
<ul>
<li>广播事务阶段</li>
<li>广播提交操作</li>
</ul>
</li>
<li><p>这两阶段提交模型如下， 有可能因为Leader宕机带来数据不一致， 比如</p>
<ul>
<li>Leader 发 起 一 个 事 务Proposal1 后 就 宕 机 ， Follower 都 没 有Proposal1</li>
<li>Leader收到半数ACK宕机，没来得及向Follower发送Commit </li>
</ul>
</li>
<li><p>怎么解决呢？ </p>
<ul>
<li>ZAB引入了崩溃恢复模式。</li>
</ul>
</li>
</ul>
<h4 id="2-2、崩溃恢复"><a href="#2-2、崩溃恢复" class="headerlink" title="2.2、崩溃恢复"></a>2.2、崩溃恢复</h4><h5 id="崩溃恢复——异常假设"><a href="#崩溃恢复——异常假设" class="headerlink" title="崩溃恢复——异常假设"></a>崩溃恢复——异常假设</h5><ul>
<li>一旦Leader服务器出现崩溃或者由于网络原因导致Leader服务器失去了与过半 Follower的联系，那么就会进入<strong>崩溃恢复模式</strong>。</li>
</ul>
<img src="https://gitee.com/kuangtf/blogImage/raw/master/img/zookeeper23.jpg" style="zoom:80%;" />

<ul>
<li>假设两种服务器异常情况：<ul>
<li>假设一个事务在Leader提出之后， Leader挂了。</li>
<li>一个事务在Leader上提交了， 并且过半的Follower都响应Ack了， 但是Leader在Commit消息发出之前挂了。</li>
</ul>
</li>
<li>Zab协议崩溃恢复要求满足以下两个要求：<ul>
<li>确保已经被Leader提交的提案Proposal， 必须最终被所有的Follower服务器提交。 （已经产生的提案， Follower必须执行）</li>
<li>确保丢弃已经被Leader提出的， 但是没有被提交的Proposal。 （丢弃胎死腹中的提案）</li>
</ul>
</li>
</ul>
<h5 id="崩溃恢复——Leader选举"><a href="#崩溃恢复——Leader选举" class="headerlink" title="崩溃恢复——Leader选举"></a>崩溃恢复——Leader选举</h5><ul>
<li>崩溃恢复主要包括两部分： <strong>Leader选举</strong>和<strong>数据恢复</strong>。</li>
</ul>
<img src="https://gitee.com/kuangtf/blogImage/raw/master/img/zookeeper24.jpg" style="zoom:67%;" />

<ul>
<li><strong>Leader选举</strong>： 根据上述要求， Zab协议需要保证选举出来的Leader需要满足以下条件：<ul>
<li>新选举出来的Leader不能包含未提交的Proposal。 即新Leader必须都是已经提交了Proposal的Follower服务器节点。</li>
<li>新选举的Leader节点中含有最大的zxid。 这样做的好处是可以避免Leader服务器检查Proposal的提交和丢弃工作。  </li>
</ul>
</li>
</ul>
<h5 id="崩溃恢复——数据恢复"><a href="#崩溃恢复——数据恢复" class="headerlink" title="崩溃恢复——数据恢复"></a>崩溃恢复——数据恢复</h5><ul>
<li>崩溃恢复主要包括两部分： Leader选举和数据恢复。</li>
<li>Zab如何数据同步：<ul>
<li>完成Leader选举后， 在正式开始工作之前（接收事务请求， 然后提出新的Proposal） ， Leader服务器会首先确认事务日<br>  志中的所有的Proposal 是否已经被集群中过半的服务器Commit。</li>
<li>Leader服务器需要确保所有的Follower服务器能够接收到每一条事务的Proposal， 并且能将所有已经提交的事务Proposal应用到内存数据中。 等到Follower将所有尚未同步的事务Proposal都从Leader服务器上同步过， 并且应用到内存数据中以后，Leader才会把该Follower加入到真正可用的Follower列表中。  </li>
</ul>
</li>
</ul>
<h3 id="3、CAP"><a href="#3、CAP" class="headerlink" title="3、CAP"></a>3、CAP</h3><ul>
<li>CAP理论告诉我们， 一个分布式系统不可能同时满足以下三种<ul>
<li>一致性（C:Consistency）</li>
<li>可用性（A:Available）</li>
<li>分区容错性（ P:Partition Tolerance）</li>
</ul>
</li>
<li>这三个基本需求， 最多只能同时满足其中的两项， 因为P是必须的， 因此往往选择就在CP或者AP中。</li>
<li>一致性（ C:Consistency）<ul>
<li>在分布式环境中， 一致性是指数据在多个副本之间是否能够保持数据一致的特性。 在一致性的需求下， 当一个系统在数据一致的状态下执行更新操作后， 应该保证系统的数据仍然处于一致的状态。</li>
</ul>
</li>
<li>可用性（A:Available）<ul>
<li>可用性是指系统提供的服务必须一直处于可用的状态， 对于用户的每一个操作请求总是能够在有限的时间内返回结果。</li>
</ul>
</li>
<li>分区容错性（ P:Partition Tolerance）<ul>
<li>分布式系统在遇到任何网络分区故障的时候， 仍然需要能够保证对外提供满足一致性和可用性的服务， 除非是整个网络<br>  环境都发生了故障。</li>
</ul>
</li>
<li>ZooKeeper保证的是CP<ul>
<li>ZooKeeper不能保证每次服务请求的可用性。 （注：在极端环境下， ZooKeeper可能会丢弃一些请求， 消费者程序需要<br>  重新请求才能获得结果） 。 所以说， ZooKeeper不能保证服务可用性。</li>
<li>进行Leader选举时集群都是不可用  。</li>
</ul>
</li>
</ul>
<blockquote>
<p>引用：</p>
<p>尚硅谷的学习笔记！</p>
</blockquote>

                
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/about" rel="external nofollow noreferrer">Gtwff</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://kuangty.gitee.io/2021/11/10/zookeeper/ZooKeeper%E7%AA%81%E5%87%BB%EF%BC%8C%E7%9C%8B%E8%BF%99%E7%AF%87%E5%B0%B1%E5%A4%9F%E4%BA%86/">https://kuangty.gitee.io/2021/11/10/zookeeper/ZooKeeper%E7%AA%81%E5%87%BB%EF%BC%8C%E7%9C%8B%E8%BF%99%E7%AF%87%E5%B0%B1%E5%A4%9F%E4%BA%86/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/about" target="_blank">Gtwff</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/Zookeeper-%E7%AA%81%E5%87%BB/">
                                    <span class="chip bg-color">Zookeeper 突击</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/2021/11/10/zookeeper/ZooKeeper%20%E7%9B%B8%E5%85%B3%E6%A6%82%E5%BF%B5%E6%80%BB%E7%BB%93%E8%BF%9B%E9%98%B6/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/5.jpg" class="responsive-img" alt="ZooKeeper相关概念进阶">
                        
                        <span class="card-title">ZooKeeper相关概念进阶</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2021-11-10
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/ZooKeeper/" class="post-category">
                                    ZooKeeper
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/ZooKeeper%E7%9B%B8%E5%85%B3%E6%A6%82%E5%BF%B5%E8%BF%9B%E9%98%B6/">
                        <span class="chip bg-color">ZooKeeper相关概念进阶</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2021/11/08/Redis/%E9%AB%98%E7%BA%A7%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/18.jpg" class="responsive-img" alt="Redis 中的高级数据结构">
                        
                        <span class="card-title">Redis 中的高级数据结构</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2021-11-08
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/Redis/" class="post-category">
                                    Redis
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Redis-%E9%AB%98%E7%BA%A7%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/">
                        <span class="chip bg-color">Redis 高级数据结构</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>



<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card" style="background-color: white;">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h1, h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h1, h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




    <footer class="page-footer bg-color">
    
        <link rel="stylesheet" href="/libs/aplayer/APlayer.min.css">
<style>
    .aplayer .aplayer-lrc p {
        
        display: none;
        
        font-size: 12px;
        font-weight: 700;
        line-height: 16px !important;
    }

    .aplayer .aplayer-lrc p.aplayer-lrc-current {
        
        display: none;
        
        font-size: 15px;
        color: #42b983;
    }

    
    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body {
        left: -66px !important;
    }

    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body:hover {
        left: 0px !important;
    }

    
</style>
<div class="">
    
    <div class="row">
        <meting-js class="col l8 offset-l2 m10 offset-m1 s12"
                   server="netease"
                   type="playlist"
                   id="503838841"
                   fixed='true'
                   autoplay='false'
                   theme='#42b983'
                   loop='all'
                   order='random'
                   preload='auto'
                   volume='0.7'
                   list-folded='true'
        >
        </meting-js>
    </div>
</div>

<script src="/libs/aplayer/APlayer.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/meting@2/dist/Meting.min.js"></script>

    

    <div class="container row center-align"
         style="margin-bottom: 15px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2019-2022</span>
            
            <span id="year">2019</span>
            <a href="/about" target="_blank">Gtwff</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
                &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                        class="white-color">577.4k</span>
            
            
            
                
            
            
                <span id="busuanzi_container_site_pv">
                &nbsp;|&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;
                    <span id="busuanzi_value_site_pv" class="white-color"></span>
            </span>
            
            
                <span id="busuanzi_container_site_uv">
                &nbsp;|&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;
                    <span id="busuanzi_value_site_uv" class="white-color"></span>
            </span>
            
            <br>

            <!-- 运行天数提醒. -->
            
                <span id="sitetime"> Loading ...</span>
                <script>
                    var calcSiteTime = function () {
                        var seconds = 1000;
                        var minutes = seconds * 60;
                        var hours = minutes * 60;
                        var days = hours * 24;
                        var years = days * 365;
                        var today = new Date();
                        var startYear = "2019";
                        var startMonth = "6";
                        var startDate = "28";
                        var startHour = "0";
                        var startMinute = "0";
                        var startSecond = "0";
                        var todayYear = today.getFullYear();
                        var todayMonth = today.getMonth() + 1;
                        var todayDate = today.getDate();
                        var todayHour = today.getHours();
                        var todayMinute = today.getMinutes();
                        var todaySecond = today.getSeconds();
                        var t1 = Date.UTC(startYear, startMonth, startDate, startHour, startMinute, startSecond);
                        var t2 = Date.UTC(todayYear, todayMonth, todayDate, todayHour, todayMinute, todaySecond);
                        var diff = t2 - t1;
                        var diffYears = Math.floor(diff / years);
                        var diffDays = Math.floor((diff / days) - diffYears * 365);

                        // 区分是否有年份.
                        var language = 'zh-CN';
                        if (startYear === String(todayYear)) {
                            document.getElementById("year").innerHTML = todayYear;
                            var daysTip = 'This site has been running for ' + diffDays + ' days';
                            if (language === 'zh-CN') {
                                daysTip = '本站已运行 ' + diffDays + ' 天';
                            } else if (language === 'zh-HK') {
                                daysTip = '本站已運行 ' + diffDays + ' 天';
                            }
                            document.getElementById("sitetime").innerHTML = daysTip;
                        } else {
                            document.getElementById("year").innerHTML = startYear + " - " + todayYear;
                            var yearsAndDaysTip = 'This site has been running for ' + diffYears + ' years and '
                                + diffDays + ' days';
                            if (language === 'zh-CN') {
                                yearsAndDaysTip = '本站已运行 ' + diffYears + ' 年 ' + diffDays + ' 天';
                            } else if (language === 'zh-HK') {
                                yearsAndDaysTip = '本站已運行 ' + diffYears + ' 年 ' + diffDays + ' 天';
                            }
                            document.getElementById("sitetime").innerHTML = yearsAndDaysTip;
                        }
                    }

                    calcSiteTime();
                </script>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/kuangtianyu" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:1575235124@qq.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=1575235124" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 1575235124" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>





    <a href="https://www.zhihu.com/people/kuang-tian-yu-59" class="tooltipped" target="_blank" data-tooltip="关注我的知乎: https://www.zhihu.com/people/kuang-tian-yu-59" data-position="top" data-delay="50">
        <i class="fab fa-zhihu1">知</i>
    </a>



    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/search.xml', 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    <!--腾讯兔小巢-->
    
    
    <script type="text/javascript" color="0,0,255"
        pointColor="0,0,255" opacity='0.7'
        zIndex="-1" count="99"
        src="/libs/background/canvas-nest.js"></script>
    

    
    
    <script type="text/javascript" size="150" alpha='0.6'
        zIndex="-1" src="/libs/background/ribbon-refresh.min.js" async="async"></script>
    

    
    <script type="text/javascript" src="/libs/background/ribbon-dynamic.js" async="async"></script>
    

    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
